package net.akkz.webRedirect.action;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.akkz.beanFactory.BeanFactory;
import net.akkz.webRedirect.service.UrlMapService;

/**
 * Servlet implementation class DefaultRedirect
 */
@WebServlet(name="DefaultRedirect", urlPatterns="/urlMap.do")
public class DefaultRedirect extends HttpServlet
{
	private static final long serialVersionUID = 1L;
	private UrlMapService urlMapService;

	/**
	 * Default constructor.
	 */
	public DefaultRedirect()
	{
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		doRedirect(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		doRedirect(request, response);
	}

	
	private void doRedirect(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		String url = request.getRequestURL().toString();
		
		int s = url.indexOf("/");
		url = url.substring(s+2);

		s = url.indexOf("/");
		url = url.substring(0, s);
		
		String map = urlMapService.getMap(url);
		
		if(map == null)
		{
			map  = urlMapService.getMap("default");
		}
		
		if(map == null)
		{
			response.sendRedirect("/jsp/errorPage.html");
			return;
		}

		request.setAttribute("map", map);
		
		request.getRequestDispatcher("/jsp/reponseUrl.jsp").forward(request, response);
	}
	
	public static void main(String[] args)
	{
		String url = "http://www.baidu.com/test";
		
		int s = url.indexOf("/");
		url = url.substring(s+2);

		s = url.indexOf("/");
		url = url.substring(0, s);
		
		System.out.println(url);
	}
	
	@Override
	public void init()
	{
		BeanFactory  bf = (BeanFactory) this.getServletContext().getAttribute("beanFactory");
		
		urlMapService = bf.getBean("urlMapService");
	}
}
